<template>
	<view class="container" :style="appThemeStyle">
		<!-- 一级分类 -->
		<scroll-view class="cate-left" :scroll-y="true" @touchmove.stop.prevent>
			<text class="type-nav" :class="{ selected: curIndex == -1 }" @click="handleSelectNav(-1)">全部</text>
			<text class="type-nav" :class="{ selected: curIndex == index }" v-for="(item, index) in list" :key="index"
				@click="handleSelectNav(index)">{{ item.name }}</text>

			<!-- 购物车的占位盒子 -->
			<view class="height-100" v-if="cartList.length > 0"></view>
		</scroll-view>
		<mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ use: false }" :up="upOption"
			:bottombar="false" @up="upCallback">

			<view class="cate-content">
				<!-- 子分类 -->
				<view v-if="subCateList.length" class="sub-cate-list clearfix" :class="{ 'display-fold': !showSubCate }"
					@touchmove.stop.prevent>
					<view class="nav-icon" @click="handleShowSubCate">
						<text class="iconfont" :class="[ showSubCate ? 'icon-arrow-up' : 'icon-arrow-down' ]"></text>
					</view>
					<view class="sub-cate-item" :class="{ selected: curIndex2 == -1 }" @click="handleSelectSubCate(-1)">
						<text>全部</text>
					</view>
					<view class="sub-cate-item" v-for="(item, index) in subCateList" :key="index"
						:class="{ selected: curIndex2 == index }" @click="handleSelectSubCate(index)">
						<text>{{ item.name }}</text>
					</view>
				</view>

				<!-- 商品列表 -->
				<view class="goods-list">
					<view class="goods-item--container" v-for="(item, index) in goodsList.data" :key="index">
						<view class="goods-item" @click="onTargetGoods(item.goods_id)">
							<!-- 商品图片 -->
							<view class="goods-item-left">
								<image class="image" :src="item.goods_image" mode="aspectFill"></image>
							</view>
							<view class="goods-item-right">
								<!-- 商品标题 -->
								<view class="goods-name">
									<text class="twoline-hide">{{ item.goods_name }}</text>
								</view>
								<!-- 商品信息 -->
								<view class="goods-item-desc">
									<view class="desc-footer">
										<view class="item-prices oneline-hide">
											<text class="price-x u-text-pink2">¥{{ item.goods_price_min }}</text>
											<text v-if="item.line_price_min > 0"
												class="price-y">¥{{ item.line_price_min }}</text>
										</view>
										<add-cart-btn v-if="setting.showAddCart" :btnStyle="setting.cartStyle"
											@handleAddCart="handleAddCart(item)" />
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 遮罩层 -->
				<view class="mask" v-show="showSubCate" @touchmove.stop.prevent @click="handleShowSubCate"></view>
				<!-- 加入购物车组件 -->
				<AddCartPopup ref="AddCartPopup" :cartTotal="cartList.length" @addCart="onUpdateCartTabBadge" />
			</view>
		</mescroll-body>


		<!-- 购物车的占位盒子 -->
		<view class="height-100" v-if="cartList.length > 0 && goodsList.data.length > 0"></view>
		<!-- 选中商品后的购物车 -->
		<view class="cart u-flex u-row-between z-index-big" v-if="cartList.length > 0">
			<!-- :class="cartShow ? 'z-index-big' : ''" -->
			<view class="cart-img">
				<image
					:src="storeInfo && storeInfo.logoImage.preview_url ? storeInfo.logoImage.preview_url : '/static/default-logo.png'"
					@click="cartShow = true"></image>
				<view class="cart-num u-flex-center">
					{{total}}
				</view>
			</view>
			<view class="u-flex">
				<view class="cart-price u-flex">
					合计
					<view class="cart-bold">￥
						<text>{{integerPart}}.</text>
						{{decimalPart}}
					</view>
				</view>
				<view class="cart-btn u-text-pink3" @click="handleOrder">去结算</view>
			</view>
		</view>
		<!-- 购物车弹窗 -->
		<u-popup v-model="cartShow" mode="bottom" border-radius="20">
			<view class="pop-cart">
				<view class="pop-tit u-flex u-row-between">
					<view class="tit-blod">已选商品</view>
					<view class="tit-grey u-flex" @click="handleDelete(1)">
						<u-icon name="trash" size="26" style="margin-top: 4rpx;"></u-icon>
						清空
					</view>
				</view>
				<view class="height-80"></view>

				<view class="pop-shop">
					<view class="cart-item u-flex" v-for="(item, index) in cartList" :key="index">
						<view class="goods-image" @click="onTargetGoods(item.goods_id)">
							<image class="image" :src="item.goods.goods_image" mode="aspectFill"></image>
						</view>
						<view class="item-content">
							<view class="goods-title" @click="onTargetGoods(item.goods_id)">
								<text class="twoline-hide">{{ item.goods.goods_name }}</text>
							</view>
							<view class="u-flex u-flex-wrap">
								<!-- 商品规格 -->
								<view class="goods-props clearfix u-flex u-flex-wrap">
									<view v-for="(props, idx) in item.goods.skuInfo.goods_props" :key="idx">
										{{ props.value.name }}{{idx == item.goods.skuInfo.goods_props.length - 1 ? '' : '/'}}
									</view>
								</view>
								<view class="goods-props">
									{{ item.goods.skuInfo.goods_props && item.ingredients_props.length == 0 ? '' : item.goods.skuInfo.goods_props && item.ingredients_props.length >0 ? '/':!item.goods.skuInfo.goods_props && item.ingredients_props.length > 0 ? '' : ''}}
								</view>
								<!-- 商品小料 -->
								<view class="goods-props clearfix u-flex u-flex-wrap">
									<view class="goods-props-item" v-for="(props, idx) in item.ingredients_props"
										:key="idx">
										{{ props.name }}{{ props.num > 1 ? '×' + props.num : ''}}{{idx == item.ingredients_props.length - 1 ? '' : '/'}}
									</view>
								</view>
							</view>
							<view class="item-foot u-flex u-row-between">
								<view class="goods-price u-text-pink2">
									<text class="unit">￥</text>
									<text
										class="value">{{ (Number(item.goods.skuInfo.goods_price) + item.ingredients_props.reduce((sum, item) => sum + (Number(item.ingredient_price) * item.num), 0)).toFixed(2)}}</text>
								</view>
								<view class="stepper">
									<u-number-box :min="1" bgColor="#fff" :modelValue="item.goods_num" :step="1"
										@minus="minusClick(item)" @change="onChangeStepper($event, item)" />
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="height-100"></view>
			</view>
		</u-popup>
		<!-- 闭店弹窗 -->
		<u-popup v-model="storeShow" mode="bottom" border-radius="20" :mask-close-able="false">
			<view class="store-pop u-flex">
				<view>
					<view class="pop-tit">
						打烊啦!
					</view>
					<view class="pop-tip">
						请在请营业时间内下单!<br>营业时间：{{start_time}}-{{end_time}}
					</view>
				</view>

				<image src="/static/new/category/close.png" mode="widthFix" class="pop-img"></image>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
	import {
		getEmptyPaginateObj,
		getMoreListData,
		// setCartTabBadge
	} from '@/core/app'
	import AddCartBtn from '@/components/add-cart-btn'
	import AddCartPopup from '@/components/add-cart-popup'
	import * as GoodsApi from '@/api/goods'
	import * as CartApi from '@/api/cart'
	import StoreModel from '@/common/model/Store'
	import StoreApi from '@/api/store'
	import {
		arrayIntersect,
		debounce
	} from '@/utils/util'
	import dayjs from 'dayjs';

	const pageSize = 15

	export default {
		components: {
			AddCartBtn,
			AddCartPopup
		},
		mixins: [MescrollMixin],
		props: {
			// 分类列表
			list: {
				type: Array,
				default: []
			},
			// 分类设置
			setting: {
				type: Object,
				default: () => {}
			},
		},
		data() {
			return {
				// 一级分类：指针
				curIndex: -1,
				// 是否显示子分类
				showSubCate: false,
				// 二级分类：指针
				curIndex2: -1,
				// 商品列表
				goodsList: getEmptyPaginateObj(),
				// 上拉加载配置
				upOption: {
					// 首次自动执行
					auto: true,
					// 每页数据的数量; 默认10
					page: {
						size: pageSize
					},
					// 数量要大于3条才显示无更多数据
					noMoreSize: 3,
					// 返回顶部
					toTop: {
						right: 30,
						bottom: 48,
						zIndex: 9
					}
				},
				// 购物车弹窗
				cartShow: false,
				// 购物车商品列表
				cartList: [],
				// 购物车商品总数量
				total: null,
				// 选中的商品ID记录
				checkedIds: [],
				// 选中的商品总金额
				totalPrice: '0.00',
				//总金额小数点前的数
				integerPart: null,
				//总金额小数点后的数
				decimalPart: null,
				// 商城基本信息
				storeInfo: undefined,
				// 营业开始时间
				start_time: null,
				// 营业结束时间
				end_time: null,
				// 闭店开关
				storeShow: false,
			}
		},
		computed: {
			// 二级分类列表
			subCateList() {
				if (this.list[this.curIndex] && this.list[this.curIndex].children) {
					return this.list[this.curIndex].children
				}
				return []
			}
		},
		created() {
			// 购物车列表
			this.getCartList()
			// 获取商城基本信息
			this.getStoreInfo()
		},
		methods: {

			/**
			 * 上拉加载的回调 (页面初始化时也会执行一次)
			 * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
			 * @param {Object} page
			 */
			upCallback(page) {
				const app = this
				// 设置列表数据
				app.getGoodsList(page.num)
					.then(list => {
						const curPageLen = list.data.length
						const totalSize = list.data.total
						app.mescroll.endBySize(curPageLen, totalSize)
					})
					.catch(() => app.mescroll.endErr())
			},

			/**
			 * 获取商品列表
			 * @param {Number} pageNo 页码
			 */
			getGoodsList(pageNo = 1) {
				const app = this
				const categoryId = app.getCategoryId()
				return new Promise((resolve, reject) => {
					GoodsApi.list({
							categoryId,
							page: pageNo
						}, {
							load: false
						})
						.then(result => {
							const newList = result.data.list
							app.goodsList.data = getMoreListData(newList, app.goodsList, pageNo)
							app.goodsList.last_page = newList.last_page

							resolve(newList)
						})
						.catch(reject)
				})
			},

			// 获取当前选择的分类ID
			getCategoryId() {
				const app = this
				if (app.curIndex2 > -1) {
					return app.subCateList[app.curIndex2].category_id
				}
				return app.curIndex > -1 ? app.list[app.curIndex].category_id : 0
			},

			// 获取商城基本信息
			getStoreInfo() {
				// StoreModel.storeInfo().then(storeInfo => this.storeInfo = storeInfo)  旧版

				StoreApi.data().then(result => {
					this.storeInfo = result.data.storeInfo
					this.start_time = result.data.storeInfo.start_time
					this.end_time = result.data.storeInfo.end_time


					setTimeout(() => {
						let currentTime = Number(dayjs().format('HHmm'))
						let start_time = Number(this.storeInfo.start_time.replace(':', ''))
						let end_time = Number(this.storeInfo.end_time.replace(':', ''))

						if (this.storeInfo.is_open == 0 || start_time > currentTime || currentTime >
							end_time) {
							this.storeShow = true
						}else{
							this.storeShow = false
						}
					}, 100)
				})
			},

			// 一级分类：选中分类
			handleSelectNav(index) {
				this.curIndex = index
				this.onRefreshList()
				this.showSubCate = false
				this.curIndex2 = -1
			},

			// 二级分类：选中分类
			handleSelectSubCate(index) {
				this.curIndex2 = index
				this.showSubCate = false
				this.onRefreshList()
			},

			// 刷新列表数据
			onRefreshList() {
				this.goodsList = getEmptyPaginateObj()
				setTimeout(() => this.mescroll.resetUpScroll(), 120)
			},

			// 跳转至商品列表页
			onTargetGoods(goodsId) {
				this.$navTo('pages/goods/detail', {
					goodsId
				})
			},

			// 点击加入购物车
			handleAddCart(item) {
				// spec_type 10单规格  20多规格
				// ingredient_type 10单规格  20多规格  30不可添加小料

				if (item.spec_type == 20 || item.ingredient_type == 10 || item.ingredient_type == 20) {
					this.onTargetGoods(item.goods_id) //跳到详情页
				} else {
					this.$refs.AddCartPopup.handle(item) //直接加入购物车
				}

				// 更新购物车
				this.onCalcTotalPrice()
			},

			// 更新购物车角标
			onUpdateCartTabBadge() {
				console.log('onUpdateCartTabBadge')
				// setCartTabBadge()

				// 更新购物车商品列表
				this.getCartList()
			},

			// 切换子分类显示状态
			handleShowSubCate() {
				this.showSubCate = !this.showSubCate
			},

			// 获取购物车商品列表
			getCartList() {
				const app = this
				app.isLoading = true
				// 用户登录后 才能用购物车信息
				if (uni.getStorageSync('userId')) {
					CartApi.list()
						.then(result => {
							app.cartList = result.data.list
							app.total = result.data.cartTotal
							// 获取选中商品id总数组
							app.onClearInvalidId()
							// 重新计算合计金额
							app.onCalcTotalPrice()
							// 判断购物车,没有商品关闭弹窗
							if (app.total == 0) {
								app.cartShow = false
							}
						})
						.finally(() => app.isLoading = false)
				}
			},

			// 获取选中商品id总数组
			onClearInvalidId() {
				this.checkedIds = this.cartList.map(item => item.id)
			},

			// 单个商品减到1,再减删除
			minusClick(item) {
				if (item.goods_num == 1) {
					this.onClearCart([item.id])
				}
			},

			// 监听步进器更改事件
			onChangeStepper({
				value
			}, item) {
				// 这里是组织首次启动时的执行
				if (item.goods_num == value) return
				// 记录一个节流函数句柄
				if (!item.debounceHandle) {
					item.oldValue = item.goods_num
					item.debounceHandle = debounce(this.onUpdateCartNum, 500)
				}
				// 更新商品数量
				item.goods_num = value
				// 商品小料
				let ingredients = item.ingredients_props.map(item => ({
					ingredientId: item.ingredient_id, // 将 id 映射为 userId
					num: item.num // 将 num 映射为 count
				}));


				// 提交更新购物车数量 (节流)
				item.debounceHandle(item, item.oldValue, value, ingredients)
				// 获取选中商品id总数组
				this.onClearInvalidId()
			},

			// 提交更新购物车数量
			onUpdateCartNum(item, oldValue, newValue, ingredients) {
				const app = this
				CartApi.update(item.goods_id, item.goods_sku_id, newValue, ingredients)
					.then(result => {
						// 更新商品数量
						app.total = result.data.cartTotal
						// 重新计算合计金额
						app.onCalcTotalPrice()
						// 清除节流函数句柄
						item.debounceHandle = null
					})
					.catch(err => {
						// 还原商品数量
						item.goods_num = oldValue
						setTimeout(() => app.$toast(err.errMsg), 10)
					})
			},

			// 计算合计金额和总杯数 (根据选中的商品)
			onCalcTotalPrice() {
				const app = this
				// 计算总金额
				let tempPrice = 0;
				app.cartList.forEach(item => {
					// 商品单价, 为了方便计算先转换单位为分 (整数)
					const unitPrice = item.goods.skuInfo.goods_price * 100
					const materialPrice = item.ingredients_props.reduce((sum, item) => sum + (Number(item
						.ingredient_price) * item.num), 0) * 100
					const allPrice = unitPrice + materialPrice
					tempPrice += allPrice * item.goods_num
				})
				app.totalPrice = (tempPrice / 100).toFixed(2)

				const parts = app.totalPrice.toString().split('.');
				app.integerPart = parts[0]; // 总金额小数点前的数
				app.decimalPart = parts[1] || "0"; // 总金额小数点后的数
			},

			// 删除选中的商品弹窗事件
			handleDelete(type, arr) {
				// type==1全部清空  type==2单个商品减到1,再减删除
				const app = this
				uni.showModal({
					title: '友情提示',
					content: '您确定要删除该商品吗？',
					showCancel: true,
					success({
						confirm
					}) {
						// 确认删除
						confirm && app.onClearCart(app.checkedIds)
					}
				})
			},

			// 确认删除商品
			onClearCart(checkedIds) {
				const app = this
				CartApi.clear(checkedIds)
					.then(result => {
						app.getCartList()
					})
			},

			// 结算选中的商品
			handleOrder() {
				const app = this
				if (app.checkedIds.length) {
					const cartIds = app.checkedIds.join()
					app.$navTo('pages/checkout/index', {
						mode: 'cart',
						cartIds
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.height-100 {
		height: 98rpx;
	}

	.container {
		padding-left: 173rpx;
	}

	// 分类内容
	.cate-content {
		z-index: 1;
		background: #fff;
		padding-top: 90rpx;
		min-height: 300rpx;
	}

	// 一级分类+二级分类 20
	.cate-left {
		position: fixed;
		top: calc(88rpx + var(--window-top));
		left: var(--window-left);
		bottom: var(--window-bottom);
		width: 173rpx;
		height: calc(100% - var(--window-top) - var(--window-bottom) - 90rpx) !important;
		background: #f8f8f8;
		color: #444;
	}

	// 左侧一级分类
	.type-nav {
		position: relative;
		height: 90rpx;
		z-index: 10;
		display: block;
		font-size: 26rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		&.selected {
			background: #fff;
			border-right: none;
			font-size: 28rpx;
			// color: $main-bg;
			color: #7ca934;
		}
	}

	// 商品列表
	.goods-list {
		background: #fff;
		position: relative;
	}

	.goods-item {
		padding: 28rpx 22rpx;
		display: flex;
	}

	.goods-item-left {
		position: relative;
		background: #fff;
		margin-right: 20rpx;

		.image {
			display: block;
			width: 150rpx;
			height: 150rpx;
			border-radius: 50%;
		}
	}

	.goods-item-right {
		position: relative;
		flex: 1;

		.goods-name {
			display: block;
			width: 100%;
			min-height: 68rpx;
			font-size: 28rpx;
			line-height: 1.3;
			color: #333;
		}
	}

	.goods-item-desc {
		margin-top: 20rpx;

		.people {
			margin-right: 14rpx;
		}

		.desc-footer {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: absolute;
			right: 0rpx;
			bottom: 0rpx;
			min-height: 44rpx;

			.item-prices {
				padding-right: 6rpx;

				.price-x {
					margin-right: 14rpx;
					font-size: 28rpx;
				}

				.price-y {
					color: #999;
					text-decoration: line-through;
					font-size: 24rpx;
				}
			}

		}
	}


	// 子分类
	.sub-cate-list {
		background-color: #fff;
		width: 100%;
		z-index: 9;
		padding: 8rpx 40rpx 0 14rpx;
		overflow: hidden;
		position: sticky;
		top: calc(88rpx + var(--window-top));

		&.display-fold {
			height: 86rpx;
		}

		.nav-icon {
			position: absolute;
			right: 16rpx;
			top: 12rpx;
			font-size: 32rpx;
		}

		.sub-cate-item {
			float: left;
			background: #f8f8f8;
			padding: 10rpx 30rpx;
			margin-right: 22rpx;
			margin-bottom: 24rpx;
			font-size: 26rpx;
			border-radius: 14rpx;
			border: 1rpx solid #f8f8f8;

			&.selected {
				// color: $main-bg;
				color: #7ca934;
				border: 1rpx solid $main-bg;
			}
		}
	}

	// 子分类遮罩层
	.mask {
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
		z-index: 8;
		background-color: rgba(0, 0, 0, 0.4);
		transition: all 0.3s ease-in-out 0s;
	}

	.z-index-big {
		z-index: 99999; //要层级比购物车弹窗高
	}

	// 购物车
	.cart {
		background: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10rpx 20rpx;
		box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.36);
		// box-shadow: 0px 3px 6px 1px rgba(35, 61, 122, 1.0);

		.cart-img {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			position: relative;

			image {
				width: 100%;
				height: 100%;
			}

			.cart-num {
				width: 30rpx;
				height: 30rpx;
				color: #fff;
				font-size: 18rpx;
				background: #ffb800;
				position: absolute;
				top: 4rpx;
				right: -14rpx;
				border-radius: 20rpx;
			}
		}

		.cart-price {
			font-size: 26rpx;

			.cart-bold {
				letter-spacing: -2rpx;
				font-weight: bold;

				text {
					font-size: 32rpx;
				}
			}
		}

		.cart-btn {
			color: #fff;
			padding: 15rpx 45rpx;
			border-radius: 15rpx;
			margin-left: 15rpx;
		}
	}

	// 购物车弹窗
	.pop-cart {
		max-height: 800rpx;
		position: relative;

		.height-80 {
			height: 90rpx;
		}


		.pop-tit {
			width: 100%;
			height: 90rpx;
			background: #fff;
			padding: 0rpx 20rpx;
			box-sizing: border-box;
			position: fixed;
			top: 0;
			z-index: 3;

			.tit-blod {
				font-weight: bold;
				font-size: 32rpx;
			}

			.tit-grey {
				color: #aaa;
				font-size: 26rpx;
			}
		}

		// 商品列表
		.pop-shop {
			.cart-item {
				background: #fff;
				padding: 0rpx 20rpx;
				margin-bottom: 30rpx;

				.goods-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					overflow: hidden;

					.image {
						display: block;
						width: 100%;
						height: 100%;
					}
				}

				.item-content {
					flex: 1;
					padding-left: 20rpx;

					.goods-title {
						font-size: 28rpx;
						max-height: 76rpx;
						font-weight: bold;
					}

					.goods-props {
						margin-top: 10rpx;
						color: #ababab;
						font-size: 23rpx;
					}

					.item-foot {
						margin-top: 10rpx;

						.goods-price {
							vertical-align: bottom;

							.unit {
								font-size: 22rpx;
							}

							.value {
								font-size: 28rpx;
							}
						}
					}
				}
			}
		}
	}

	// 闭店弹窗
	.store-pop {
		padding: 80rpx 40rpx 120rpx;

		.pop-tit {
			color: #333;
			font-weight: bold;
			font-size: 38rpx;
		}

		.pop-tip {
			color: #a8a8a6;
			font-size: 24rpx;
			margin-top: 30rpx;
			line-height: 35rpx;
		}

		.pop-img {
			width: 150rpx;
			margin-left: 80rpx;
		}
	}
</style>